<template>
	<view>
		<u-sticky bgColor="#fff">
			<view id="topBox">
				<template v-if="msupplier_id">
					<!-- <view class="wrapper flex">
					<view class="text-gray mr15">
						选择供应商
					</view>
					<view class="flex-1">
						<picker @change="bind_picker_change" :value="picker_index" :range="org_material_rel"
							range-key="supplier_nick_name">
							<view class="blank20"></view>
							<view class="flex" >
								<view class="flex-1 text-ellipsis font-bold" v-if="org_material_rel[picker_index]">
									{{org_material_rel[picker_index].supplier_nick_name}}
								</view>
								<view class="flex-1 text-gray" v-else>
									请选择
								</view>
								<view class="ml5">
									<u-icon name="arrow-down" color="#999999" size="14"></u-icon>
								</view>
							</view>
							<view class="blank20"></view>
						</picker>
					</view>
				</view> -->
					<view class="blank20"></view>
					<view class="wrapper">
						<text class="text-gray mr15">
							供应商
						</text>
						<text class="font-bold"
							v-if="org_material_rel.length>0">{{org_material_rel[picker_index].supplier_nick_name}}</text>
					</view>
					<view class="blank20"></view>
					<u-line></u-line>
					<u-tabs :list="tabs" @click="tabClick" :activeStyle="activeStyle" lineColor="#675f91" :current="current">
						<view slot="right" style="padding-right: 10px;">
							<view class="flex">
								<u-button type="primary" size="mini" text="食材列表" @click="toFood" v-if="current == 0"></u-button>
							</view>
						</view>
					</u-tabs>
					<u-line></u-line>
				</template>
				<template v-if="current == 0">
					<search @choose="chooseSearch" page="warehousingEdit" :data="material_item" namekey="mname" :add="false">
					</search>
					<u-line></u-line>
				</template>
				<view class="flex bg-gray" v-if="current == 0">
					<template v-for="col in tableHd0">
						<view class="col-item font-24" :style="[col.style]">
							{{col.title}}
						</view>
					</template>
				</view>
				<view class="flex bg-gray" v-if="current == 1">
					<template v-for="col in tableHd1">
						<view class="col-item font-24" :style="[col.style]">
							{{col.title}}
						</view>
					</template>
				</view>
				<u-line></u-line>
			</view>
		</u-sticky>
		<scroll-view scroll-y scroll-with-animation :style="{'height':scrollHeight+'px'}">
			<template v-if="current == 0">
				<u-checkbox-group v-model="checkboxValue" placement="column" @change="checkboxChange">
					<template v-for="(v,index) in list0">
						<item :table="tableHd0" :detail="v" @del="delItem" :unit="material_unit_obj[v.material_id]"
							:msupplier_id="msupplier_id" @updata="updataItem">
							<!-- :msupplier="org_material_rel" -->
							<!-- @pickerMsupplier="openMsupplierPicker" -->
							<view slot="mname">
								<u-checkbox :key="index" :name="index" :label="v.mname" activeColor="#675f91" shape="circle"
									labelSize="14"></u-checkbox>
							</view>
							<view slot="msupplier_id" v-if="!msupplier_id">
								<view class="flex" @click="openMsupplierPicker" :data-name="index">
									<view class="flex-1">
										{{msupplierObj[v.msupplier_id].supplier_nick_name}}
									</view>
									<view class="ml5">
										<u-icon name="arrow-down" color="#999999" size="14"></u-icon>
									</view>
								</view>
							</view>
						</item>
					</template>
				</u-checkbox-group>
			</template>
			<template v-if="current == 1">
				<template v-for="v in list1">
					<batch :table="tableHd1" :detail="v" @del="delBatch" @updata="updataBatch"></batch>
				</template>
			</template>
		</scroll-view>

		<view class="blank90"></view>

		<view class="bgw fixed-bottom">
			<u-line></u-line>
			<view class="flex">
				<view class="flex-1" style="padding-left: 15px;" v-if="current == 0">
					<u-checkbox-group placement="column" v-model="checkboxAllValue" @change="checkboxAllChange">
						<u-checkbox :key="0" :name="0" label="全选" activeColor="#675f91" shape="circle"></u-checkbox>
					</u-checkbox-group>
				</view>
				<view class="ml15 mr15" v-if="current == 0">
					<text class="font-22 text-light-gray">金额：</text>
					<text class="text-red">￥{{sum_price}}</text>
				</view>
				<view class="flex-1" v-if="current == 1">

				</view>
				<!-- disabled -->
				<view class="save-btn" @click="save">
					入库
				</view>
			</view>
		</view>

		<msupplierPicker :show="msupplierPickerShow" :msupplier="msupplier" @confirm="msupplierPickerConfirm"
			@cancel="msupplierPickerCancel" v-if="msupplier.length>0"></msupplierPicker>
	</view>
</template>

<script>
	import {
		create_new_stock_in,
		to_be_stock_one_supplier_detail,
		confirm_stock_in,
		manual_stock_in
	} from "@c/api.js";
	// import cellGroup from "../../uni_modules/uview-ui/libs/config/props/cellGroup";
	import item from './components/item.vue';
	import batch from './components/batch.vue';
	import msupplierPicker from '@/pagesA/components/msupplier-picker.vue';
	import search from "@/components/search.vue";

	let today = new Date();
	let today_year_month_day = `${today.getFullYear()}` + `-` + `${today.getMonth()+1}`.padStart(2, '0') + `-` +
		`${today.getDate()}`.padStart(2, '0');
	let date = new Date(today.getTime() + (24 * 60 * 60 * 1000 * 1)); //明天
	let year_month_day = `${date.getFullYear()}` + `-` + `${date.getMonth()+1}`.padStart(2, '0') + `-` +
		`${date.getDate()}`.padStart(2, '0');

	export default {
		components: {
			item,
			search,
			batch,
			msupplierPicker
		},
		data() {
			return {
				from: '',
				checkboxValue: [],
				checkboxAllValue: [0],
				bagList: [],
				msupplier_id: 0,
				picker_index: 0,
				org_material_rel: [],
				material_unit_obj: {},
				current: 0,
				tabs: [{
					name: '数量入库'
				}, {
					name: '批次入库'
				}],
				activeStyle: {
					color: '#675f91'
				},
				keyword: '',
				resultList: [],
				material_item: [],
				material_Obj: {},
				list0: [],
				tableHd0: [{
						title: "食材",
						key: "mname",
						style: {
							width: '200rpx'
						}
					},
					{
						title: "单价",
						key: "purchase_unit_price",
						style: {
							flex: 1
						}
					},
					{
						title: "数量",
						key: "purchase_unit_qty",
						style: {
							flex: 1
						}
					},
					{
						title: "单位",
						key: "purchase_unit_id",
						style: {
							flex: 1
						}
					},
					{
						title: "金额",
						key: "price",
						style: {
							width: '140rpx'
						}
					},
					// {
					// 	title: "入库方式",
					// 	key: "stock_in_way",
					// 	style: {
					// 		flex: 1
					// 	}
					// },
					// {
					// 	title: "",
					// 	key: "action",
					// 	style: {
					// 		width: '50px'
					// 	}
					// },

				],
				list1: [],
				tableHd1: [{
						title: "类别",
						key: "mbatch_name",
						style: {
							width: '150rpx'
						}
					},
					{
						title: "数量",
						key: "mbatch_amount",
						style: {
							flex: 1
						}
					},
					{
						title: "批次条数",
						key: "mbatch_count",
						style: {
							flex: 1
						}
					},
					{
						title: "",
						key: "action",
						style: {
							width: '100rpx'
						}
					},
				],
				msupplier: [],
				msupplierObj: {},
				msupplierPickerShow: false,
				msupplierPickerKey: '',
				// sum_price:0
				scrollHeight: 0
			}
		},
		computed: {
			sum_price() {
				let num = 0;
				let to_stock_in_list = this.list0.filter((v, i) => this.checkboxValue.includes(i));
				to_stock_in_list.forEach(v => {
					if (v.purchase_unit_price && v.purchase_unit_qty) {
						num += v.purchase_unit_price * v.purchase_unit_qty
					}
				});
				num = this.formatPrice(num);
				return num;
			}
		},
		methods: {
			msupplierPickerCancel(e) {
				this.msupplierPickerShow = false;
			},
			msupplierPickerConfirm(e) {
				let key = this.msupplierPickerKey;
				this.msupplierPickerShow = false;
				this.list0[key].msupplier_id = e.id;
				// this.list0[key].supplier_id_name = e.label;
			},
			openMsupplierPicker(e) {
				let key = e.currentTarget.dataset.name;
				this.msupplierPickerKey = Number(key);
				this.msupplierPickerShow = true;
			},
			checkboxChange(e) {
				if (e.length == this.list0.length) {
					this.checkboxAllValue = [0];
				} else {
					this.checkboxAllValue = [];
				}
			},
			checkboxAllChange(e) {
				if (e.length == 0) {
					this.checkboxValue = [];
				} else {
					let checkboxValue = [];
					this.list0.forEach((v, i) => {
						checkboxValue.push(i);
					})
					this.checkboxValue = checkboxValue;
				}
			},
			checkAll() {
				let checkboxValue = [];
				this.list0.forEach((v, i) => {
					checkboxValue.push(i);
				})
				this.checkboxValue = checkboxValue;
			},
			toFood() {
				let bagList = [];
				this.list0.forEach(v => {
					bagList.push({
						id: v.material_id,
						name: v.mname,
						value: v.purchase_unit_qty
					})
				});
				let bagListStr = JSON.stringify(bagList);
				this.nav("/warehousingFood/warehousingFood?isBack=1&bagList=" + bagListStr);
			},
			bind_picker_change(e) {
				let value = e.detail.value;
				this.picker_index = value;
			},
			chooseSearch(id) {
				this.updataList0FromBagList([{
					id: id
				}]);
				
				// console.log(this.material_unit_obj[id]);
			},
			tabClick(e) {
				if(this.current != e.index){
					this.current = e.index;
					if(this.current == 0){
						this.scrollHeight = this.scrollHeight-34;
					}else{
						this.scrollHeight = this.scrollHeight+34;
					}
				}
				// console.log(this.list);
				// this.$forceUpdate();
			},
			delItem(data) {
				this.list0 = this.list0.filter(v => v.material_id != data.material_id);
			},
			delBatch() {
				this.list1 = this.list1.filter(v => v.mbatch_id != data.mbatch_id);
			},
			updataItem(data) {
				console.log(data);
				// #ifdef MP-WEIXIN
				let index = this.list0.findIndex(v => v.material_id == data.material_id);
				// this.list0[index] = data;
				this.$set(this.list0, index, data)
				// #endif
			},
			updataBatch(data) {
				// #ifdef MP-WEIXIN
				let index = this.list1.findIndex(v => v.mbatch_id == data.mbatch_id);
				this.list1[index] = data;
				// #endif
			},
			save() {
				let to_stock_in_list = this.list0.filter((v, i) => this.checkboxValue.includes(i));
				let to_stock_in_batch_list = JSON.parse(JSON.stringify(this.list1));
				if (this.msupplier_id && to_stock_in_batch_list.length == 0 && to_stock_in_list.length == 0) {
					uni.$u.toast('请至少选择一项');
					return;
				}
				if (!this.msupplier_id && to_stock_in_list.length == 0) {
					uni.$u.toast('请至少选择一项');
					return;
				}

				uni.showLoading({
					title: "加载中",
				});
				if (this.msupplier_id) {
					let msupplier_id = this.org_material_rel[this.picker_index].id;
					confirm_stock_in({
							to_stock_in_list,
							msupplier_id,
							to_stock_in_batch_list
						}).then((res) => {
							uni.$u.toast('保存成功');

							setTimeout(() => {
								uni.$emit('refresh_warehousing');
								uni.$u.route({
									type: 'navigateBack'
								})
							}, 2000)
						})
						.finally(() => {
							uni.hideLoading();
							uni.stopPullDownRefresh();
						});
				} else {
					manual_stock_in({
							to_stock_in_list
						}).then((res) => {
							uni.$u.toast('保存成功');
							setTimeout(() => {
								uni.$emit('refresh_warehousing');
								uni.$emit('refresh_stockDetail');
								uni.$u.route({
									type: 'navigateBack',
									delta: 2
								})
							}, 2000)
						})
						.finally(() => {
							uni.hideLoading();
							uni.stopPullDownRefresh();
						});
				}
			},
			getData() {
				uni.showLoading({
					title: "加载中",
				});
				create_new_stock_in().then((res) => {
						let {
							material_item,
							material_item_bom_unit_ratio,
							msupplier,
							unlinked_material_list
						} = res.result;
						
						let update_value = {
							updateArr:material_item,
							delIds:unlinked_material_list
						};
						this.$store.commit('update_material_item', update_value);
						let all_material_item = this.$store.getters.get_material_item;
						let all_material_obj = this.$store.getters.get_material_obj;
						this.material_item = all_material_item;
						this.material_obj = all_material_obj;
						
						this.org_material_rel = msupplier;
						this.msupplier = msupplier;
						this.msupplierObj = this.toObj(msupplier,'id');
						
						this.material_unit_obj = this.$store.getters.get_material_unit_obj;
						this.updataList0FromBagList(this.bagList);
					})
					.finally(() => {
						uni.hideLoading();
						uni.stopPullDownRefresh();
					});
			},
			getDetail() {
				let msupplier_id = this.msupplier_id;
				uni.showLoading({
					title: "加载中",
				});
				to_be_stock_one_supplier_detail({
						msupplier_id: msupplier_id
					}).then(res => {
						// console.log(res);
						let {
							// material_item,
							// material_item_bom_unit_ratio,
							// org_material_rel,
							stock_in_po_trans_batch_ids,
							stock_in_po_transient_ids
						} = res.result;
						
						let all_material_item = this.$store.getters.get_material_item;
						let all_material_obj = this.$store.getters.get_material_obj;
						this.material_item = all_material_item;
						this.material_obj = all_material_obj;
						this.material_unit_obj = this.$store.getters.get_material_unit_obj;
						
						let org_material_rel = this.$store.getters.get_msupplier
						this.org_material_rel = org_material_rel;
						this.msupplierObj = this.toObj(org_material_rel,'id');
						
						// this.material_item = material_item;
						// this.set_material_obj();
						// this.set_material_unit_obj(material_item_bom_unit_ratio);

						this.picker_index = org_material_rel.findIndex(v => v.id == this.msupplier_id);
						let list0 = [];
						stock_in_po_transient_ids.forEach(v => {
							let material = this.material_obj[v.id];
							list0.push({
								msupplier_id: msupplier_id,
								material_id: v.material_id[0],
								mname: v.material_id[1],
								purchase_unit_price: this.formatPrice(v.purchase_unit_price),
								purchase_unit_id: v.purchase_unit_id[0],
								purchase_unit_qty: v.purchase_unit_qty,
								stock_in_way: v.stock_in_way,
								org_po_detail_id: v.org_po_detail_id[0],
								need_date: v.need_date,
								id: v.id,
								material_top_category_id: v.material_top_category_id[0],
								date:this.today_year_month_day
							});
						});
						this.list0 = list0;
						this.checkAll();
						let list1 = [];
						stock_in_po_trans_batch_ids.forEach(v => {
							list1.push({
								...v,
								mbatch_name: v.mbatch_id[1],
								mbatch_id: v.mbatch_id[0],
							});
						});
						this.list1 = list1;
					})
					.finally(() => {
						uni.hideLoading();
						uni.stopPullDownRefresh();
					});
				// this.updataList0(this.bagList)
			},
			// 手工入库
			updataList0FromBagList(data) {
				let msupplier_id = this.msupplier_id;
				data.forEach(v => {
					let _index = this.list0.findIndex(d => d.material_id == v.id);
					if (_index == -1) {
						let material = this.material_obj[v.id];
						let item = {
							msupplier_id: msupplier_id || material.default_msupplier_id,
							material_id: v.id,
							mname: material.mname,
							purchase_unit_price: this.formatPrice(material.purchase_unit_price),
							purchase_unit_id: material.purchase_unit_id,
							purchase_unit_qty: v.value || 1,
							stock_in_way: material.stock_in_way || 'stock_in'
						};
						if (msupplier_id) {
							item.org_po_detail_id = 0;
							item.need_date = year_month_day;
							item.id = 0;
							item.material_top_category_id = 0;
						} else {
							item.cash_amount = ''
						}
						item.date = this.today_year_month_day;
						// console.log(item);
						this.list0.push(item);
					} else {
						v.value && (this.list0[_index].purchase_unit_qty = v.value);
					}
				})
				// console.log(this.list0);
				this.checkAll();
			},
		},
		onLoad(d) {
			// d.id = '22';
			this.from = d.from || '';
			

			if (d.bagList) {
				this.bagList = JSON.parse(d.bagList);
			}
			// this.bagList = [{
			// 		id: 360148,
			// 		name: "方肉片",
			// 		value: 1
			// 	},
			// 	{
			// 		id: 360149,
			// 		name: "猪整方肉",
			// 		value: 1
			// 	},
			// 	{
			// 		id: 360156,
			// 		name: "猪心",
			// 		value: 1
			// 	},
			// ];
			if (d.id) {
				this.msupplier_id = Number(d.id);
				this.getDetail()
			} else {
				this.msupplier_id = 0;
				this.getData();
			}
			uni.$on('warehousingFoodBack', this.updataList0FromBagList)
		},
		onShow() {},
		onReady() {
			uni.createSelectorQuery().select('#topBox').boundingClientRect(data => {
				let bottomHeight = uni.upx2px(90);
				this.scrollHeight = this.getClineHeight() - data.height - bottomHeight;
			}).exec()
		},
		onPullDownRefresh() {
			// this.getData();
		},
	}
</script>

<style lang="scss" scoped>
	.search-box {
		position: relative;
	}

	.search-result {
		z-index: 999;
		position: absolute;
		top: 32px;
		left: 0;
		right: 0;
	}

	.tag-wrapper {
		padding: 0 25upx;
	}

	.tag-item {
		margin: 5upx;
	}

	/deep/.col-item {
		padding: 20upx 10upx;
		text-align: center;
	}

	/deep/.input_border_bottom {
		line-height: 72upx;
		height: 72upx;
		font-size: 28upx;
		border-bottom: 1px solid #cccccc;
	}

	/deep/.input_border_bottom_red {
		color: #D6251F;
		border-bottom: 1px solid #D6251F;
	}

	.save-btn {
		height: 90upx;
		line-height: 90upx;
		width: 300upx;
		text-align: center;
		background-color: #675f91;
		color: #ffffff;
	}

	.save-btn.disabled {
		opacity: 0.5;
	}

	.blank90 {
		height: 90upx;
	}
</style>